import os,re
import urllib3
import dohttp
from math import floor
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def sendreq()->str:
    Header = {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0"   
        }
    res = dohttp.post(url="https://a.stu.edu.cn/ac_portal/userflux",headers=Header,verify=False,allow_redirects=True)
    if res == "error":
        return "error"
    try:
        r = res.content.decode("utf-8")
    except Exception as e:
        return "请求剩余流量时出错"
    return r
def get_usage_percent(data)->int:
    data = re.findall("<tr> <td>([^<]*)</td> <td>([^<]*)",data)
    limit = 0
    now = 0
    for a,b in data:
        if a.find("流量额") != -1:
            limit = floor(float(typetrans(b)))
        elif a.find("当天") != -1:
            now = floor(float(typetrans(b)))
    if limit == 0 or now == 0:
        return 0
    return floor(now/limit*100)   
#G->M
def typetrans(b):
    b = b.replace("M","")
    if b.find("G") != -1:
        b = b.replace("G","")
        b = str(float(b)*1024) 
    return b
if __name__ == "__main__":
        data = re.findall("<tr> <td>([^<]*)</td> <td>([^<]*)",sendreq())
        os.system("cls")
        for a,b in data:
            print(f"{a} {b}")
        print(f"{get_usage_percent(data)}%")


    
